package com.real8.plusplayground.client.person;

import com.google.api.gwt.services.plus.shared.Plus;
import com.google.gwt.activity.shared.AbstractActivity;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.ui.AcceptsOneWidget;
import com.google.web.bindery.requestfactory.shared.Receiver;
import com.real8.plusplayground.client.ClientFactory;

public class PersonActivity extends AbstractActivity implements
		PersonView.Presenter {
	private final ClientFactory clientFactory;
	private PersonView view;

	private final PersonPlace place;

	public PersonActivity(ClientFactory clientFactory, PersonPlace place) {
		this.clientFactory = clientFactory;
		this.place = place;
	}

	@Override
	public void start(final AcceptsOneWidget panel, EventBus eventBus) {
		// initialize view
		view = clientFactory.getPersonView();
		view.setPresenter(this);

		// set id
		final String personId = place.getPersonId();
		view.setId(personId);

		// check for "me"
		if (personId.equalsIgnoreCase("me")) {
			// TODO investigate checking first if already logged in
			clientFactory.login(new Receiver<String>() {
				@Override
				public void onSuccess(String authorizationToken) {
					clientFactory.createNewPlus(authorizationToken,
							new Receiver<Plus>() {
								@Override
								public void onSuccess(Plus response) {
									getAndSetActivity(personId);
								}
							});
				}
			});

		} else {
			getAndSetActivity(personId);
		}

		// set view as panel widget
		panel.setWidget(view.asWidget());
	}

	private void getAndSetActivity(final String personId) {
		// check for plus
		Plus plus = clientFactory.getPlus();
		if (plus != null) {
			plus.people()
					.get(personId)
					.to(new Receiver<com.google.api.gwt.services.plus.shared.model.Person>() {
						@Override
						public void onSuccess(
								com.google.api.gwt.services.plus.shared.model.Person person) {
							// push Activity into editor
							view.getEditorDriver().edit(person);

							// log
							println("Shown: Person with id=" + person.getId());
						}
					}).fire();
		} else {
			println("Warning: Plus RequestFactory not (yet) initialized");
		}
	}

	private void println(String value) {
		clientFactory.getShell().println(value);
	}

	@Override
	public void onIdChange(String personId) {
		clientFactory.getPlaceController().goTo(new PersonPlace(personId));
	}
}
